# coding:utf-8
import shutil

import facade
from bs4 import BeautifulSoup
import sys
import os

from xjlibrary.mdatetime.mtime import getTodayDate
from xjlibrary.mdatetime.mtime2 import MDateTimeUtils
from xjlibrary.our_file_dir import BaseDir

from id_encode import GetLngid

curPath = BaseDir.get_file_dir_absolute(__file__)

WANFANG_BZ = 'WANFANG_STANDARD_'
provider = 'wangfangstandard'
sGUrl = r'http://192.168.52.10:8080/adksvod/PublicFolder/Player/VideoPlay.aspx?VideoID='
ISOTIMEFORMAT = '%Y%m%d'
sqlList = list()
nCount = 0
CountryDict = {'中国': 'CN', '英国': 'UK', '日本': 'JP', '美国': 'US',
               '法国': 'FR', '德国': 'DE', '韩国': 'KR', '国际': 'UN'}
LanguageDict = {'CN': 'ZH', 'UK': 'EN', 'US': 'EN',
                'JP': 'JA', 'FR': 'FR', 'DE': 'DE', 'UN': 'UN', 'KR': 'KO'}


def copyTempDB3(temp_path, copy_out):
    """
    拷贝创建新的db3文件
    :param temp_path: 模板db3文件路径
    :param copy_out: 新的db3输出路径
    :return: 新db3路径
    """
    today_str = str(getTodayDate())
    if not os.path.isfile(temp_path) or not os.path.isdir(copy_out):
        raise FileNotFoundError
    new_db3_name = 'mirroradksvideo_' + today_str + '.db3'
    new_db3_path = os.path.join(copy_out, new_db3_name)
    shutil.copyfile(temp_path, new_db3_path)
    return new_db3_path


logger = facade.get_streamlogger()
db3Path = BaseDir.get_new_path(curPath, "db3")
temp_db3 = os.path.join(curPath, "zt_template", "zt_template.db3")
new_db3_path = copyTempDB3(temp_db3, db3Path)
dbsqlutils = facade.Sqlite3Utiles(logger=logger).Sqlite3DBConnectFromFilePath(
    new_db3_path, encoding="utf-8")


# 转移字符
def sqliteEscape(keyWord):
    keyWord = keyWord.replace('/', '//')
    keyWord = keyWord.replace("'", "''")
    keyWord = keyWord.replace("[", "/[")
    keyWord = keyWord.replace("]", "/]")
    keyWord = keyWord.replace("%", "/%")
    keyWord = keyWord.replace("&", "/&")
    keyWord = keyWord.replace("_", "/_")
    keyWord = keyWord.replace("(", "/(")
    keyWord = keyWord.replace(")", "/)")

    return keyWord


# 插入数据库
def InsertIntoDb():
    global sqlList, nCount
    dbsqlutils.ExeSqlliteList(sqlList)
    sqlList = list()


# 解析目标文件
def AnalysisFile(filePath):
    global sqlList
    with open(filePath, mode='r', encoding='utf-8') as f:
        line = f.readline()
        f.close()
    prefixIndex = line.find('★')
    if not prefixIndex > 0:
        print('failed find mark')
        sys.exit(-1)
    prefix = line[:prefixIndex]
    vid = prefix.split('\t')[0]
    catalog = prefix.split('\t')[1]
    timespan = prefix.split('\t')[2]
    pubdate = prefix.split('\t')[3].replace('-', '')
    year = pubdate[:4]
    html = line[prefixIndex + 1:]

    soup = BeautifulSoup(html, 'lxml')
    # 标题
    title = ''.join(soup.find('h4').stripped_strings)
    # 作者
    creator = ''.join(soup.find('dd', class_='ys').stripped_strings)

    dls = soup.find_all('dl', class_='introduction')
    # 导师简介
    creator_bio = ''.join(dls[0].stripped_strings).replace('讲师简介：暂无', '')
    # 视频简介
    description = ''.join(dls[1].stripped_strings)
    if description == '视频简介：':
        description = ''
    # 转义字符
    title = sqliteEscape(title)
    creator = sqliteEscape(creator)
    creator_bio = sqliteEscape(creator_bio)
    description = sqliteEscape(description)

    type_ = '10'
    language = 'ZH'
    country = 'CN'
    sub_db_id = "00076"
    product = "DMT"
    sub_db = "CTGU"
    provider = "ADKS"
    provider = 'mirroradksvideo'
    provider_id = provider + '@' + vid
    provider_url = provider + '@' + sGUrl + vid
    lngid = GetLngid(sub_db_id, vid)
    batch = MDateTimeUtils.get_today_date_strings() + "00"
    medium = "2"

    sql = "INSERT INTO modify_title_info_zt(lngid, rawid, title, identifier_standard, creator, creator_bio, \
		date, description, date_created, language, country, type, provider, provider_id, provider_url, provider_subject, folio_size,\
		batch,medium) VALUES('{lngid}', '{rawid}', '{title}', '{rawid}', '{creator}', '{creator_bio}', '{date}', '{description}', \
		'{date_created}', '{language}', '{country}', '{type}', '{provider}', '{provider_id}', '{provider_url}', \
		'{provider_subject}', '{folio_size}','{batch}','{medium}')".format(lngid=lngid, rawid=vid, title=title, creator=creator,
                                                      creator_bio=creator_bio,
                                                      date=year, description=description, date_created=pubdate,
                                                      language=language, country=country,
                                                      type=type_, provider=provider, provider_id=provider_id,
                                                      provider_url=provider_url, provider_subject=catalog,
                                                      folio_size=timespan,batch=batch,medium=medium)
    sqlList.append(sql)

    if len(sqlList) > 100:
        InsertIntoDb()


# ---------------------------------作业开始---------------------------------

if __name__ == '__main__':
    rootdir = os.path.join(curPath, "Detail")
    if not os.path.exists(rootdir):
        print('目录不存在:' + rootdir)
        sys.exit(-1)
    for filePath in BaseDir.get_dir_all_files(rootdir):
        print(filePath)
        AnalysisFile(filePath)
    if len(sqlList) > 0:
        InsertIntoDb()
